from __future__ import absolute_import
from pkgr.repogeneric import RepoGeneric
from pkgr.util import calc_cookie_file
import solv

import os
import rpm
import logging
logger = logging.getLogger('pkgr.RepoSystem')

class RepoSystem(RepoGeneric):
    def add_too_pool(self, pool):
        handle = pool.add_repo(self.name)
        handle.appdata = self
        self.set_solv_handle(handle)
        
        pool.installed = self.get_solv_handle()
        root = self.join_root_dir('var','lib','rpm','Packages')
        
        if not os.path.exists(root):
            rootdir =  os.path.join(self.get_root_dir(), 'var', 'lib', 'rpm')
            rpm.addMacro("_dbpath", rootdir)
            logger.debug('Initializing rpm db at %s', self.get_root_dir())
            ts = rpm.TransactionSet(self.get_root_dir())
            ts.initDB()
            rpm.delMacro("_dbpath")
            
        logger.debug('Using root %s', self.get_root_dir())
        # TODO: handle caching
        self.get_solv_handle().add_rpmdb_root(None, self.get_root_dir(), solv.Repo.REPO_REUSE_REPODATA)
        logger.debug('Writing system repo cache...')
        self.writecachedrepo(None)
        return True
